#!/usr/bin/env python3

import os

import common

class QemuComponent(self.Component):
    def add_parser_arguments(self, parser):
        parser.add_argument(
            '--userland',
            default=False,
            help='Build QEMU user mode instead of system.',
        )
        parser.add_argument(
            'extra_config_args',
            default=[],
            metavar='extra-config-args',
            nargs='*'
        )

    def do_build(self, args):
        build_dir = self.get_build_dir(args)
        os.makedirs(build_dir, exist_ok=True)
        if kwargs['verbose']:
            verbose = ['V=1']
        else:
            verbose = []
        if kwargs['userland']:
            target_list = '{}-linux-user'.format(kwargs['arch'])
        else:
            target_list = '{}-softmmu'.format(kwargs['arch'])
        self.sh.run_cmd(
            [
                os.path.join(kwargs['qemu_src_dir'], 'configure'), LF,
                '--enable-debug', LF,
                '--enable-trace-backends=simple', LF,
                '--target-list={}'.format(target_list), LF,
                '--enable-sdl', LF,
                '--with-sdlabi=2.0', LF,
            ] +
            self.sh.add_newlines(kwargs['extra_config_args']),
            extra_paths=[kwargs['ccache_dir']],
            cwd=build_dir
        )
        self.sh.run_cmd(
            (
                [
                    'make', LF,
                    '-j', str(kwargs['nproc']), LF,

                ] +
                verbose
            ),
            cwd=build_dir,
            extra_paths=[kwargs['ccache_dir']],
        )

    def get_build_dir(self, args):
        return kwargs['qemu_build_dir']

if __name__ == '__main__':
    QemuComponent().build()
